package com.apobates.jforum.grief.schema2doc.core.strategy;

import com.apobates.jforum.grief.schema2doc.core.SchemaTableStrategy;
import com.apobates.jforum.grief.schema2doc.core.schema.SchemaDialect;
import java.util.Optional;
import java.util.function.Predicate;

/**
 * 基于表名前缀的匹配模式
 * 例：think_. 要求格式符合: {prefix}_???
 */
public class SchemaTablePrefixStrategy implements SchemaTableStrategy {
    private final String prefix;

    /**
     * 初始化
     * 要求格式符合: {prefix}_???
     * @param prefix
     */
    public SchemaTablePrefixStrategy(String prefix) {
        this.prefix = prefix;
    }


    @Override
    public Optional<String> sql(SchemaDialect dialect) {
        // TABLE_NAME LIKE {}_%@各方言对于这种格式结果不同
        if(dialect == SchemaDialect.MySQL || dialect == SchemaDialect.MariaDB){
            // INSERT(TABLE_NAME, 'oams_')>0 | INSTR(str,substr) INSTR() performs a case-insensitive search. If any argument is NULL, returns NULL.
            return Optional.of(String.format("INSTR(%s, '%s') = 1", placeholder, prefix.concat("_")));
        }
        if(dialect == SchemaDialect.SQLServer){
            // CHARINDEX('JB_', a.name) = 1
            return Optional.of(String.format("CHARINDEX('%s', %s) = 1", prefix.concat("_"), placeholder));
        }
        if(dialect == SchemaDialect.Oracle){
            // INSTR(TABLE_NAME, 'PUB_')=1
            return Optional.of(String.format("INSTR(%s, '%s') = 1", placeholder, prefix.concat("_")));
        }
        if (dialect == SchemaDialect.PostgreSQL){
            // POSITION('sys_' in relname) = 1
            // https://www.postgresql.org/docs/11/functions-string.html
            // version 11+ starts_with
            return Optional.of(String.format("POSITION('%s' in %s) = 1", prefix.concat("_"), placeholder));
        }
        if(dialect == SchemaDialect.SQLite){
            // INSTR(name, 'sys_')=1
            // https://www.sqlitetutorial.net/sqlite-functions/sqlite-instr/
            return Optional.of(String.format("INSTR(%s, '%s') = 1", placeholder, prefix.concat("_")));
        }
        if (dialect == SchemaDialect.Informix){
            // instr(tabname, 'qblob_')=1
            // https://www.ibm.com/docs/en/informix-servers/14.10?topic=functions-instr-function
            return Optional.of(String.format("INSTR(%s, '%s') = 1", placeholder, prefix.concat("_")));
        }
        // return Optional.of(placeholder.concat(" LIKE '").concat(prefix).concat("_%'"));
        return Optional.empty();
    }

    @Override
    public Predicate<String> filter() {
        return passFilter();
    }
}
